package com.chuangan.releasetask.controller;

import com.alibaba.fastjson.JSONObject;
import com.chuangan.releasetask.Utils.PayCommonUtil;
import com.chuangan.releasetask.Utils.ResultVOUtil;
import com.chuangan.releasetask.VO.ResultVO;
import com.chuangan.releasetask.dto.WebDTO;
import com.chuangan.releasetask.pojo.User;
import com.chuangan.releasetask.service.PayService;
import com.chuangan.releasetask.service.UserService;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Author: zihua
 * @Date: 2020/6/5 14:37
 * @Version 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/pay")
public class PayController {



    @Autowired
    private PayService payService;

    @Autowired
    private UserService userService;











    /**
     * 功能描述: 用户余额
     * @Return:
     * @Author: jinLong
     * @Date: 2020/9/17 15:03
     */
    @GetMapping("/balance")
    public ResultVO balance(@RequestParam("userAccount") String userAccount){
        User oneUser = userService.findOneUser(userAccount);
        return ResultVOUtil.success(oneUser);
    }

    /**
     * 功能描述: APP充值
     * @Return:
     * @Author: jinLong
     * @Date: 2020/9/17 15:45
     */
    @PostMapping("/recharge")
    public ResultVO recharge(@RequestParam("addmoney") String addmoney,@RequestParam("userAccount") String userAccount){

        if (addmoney==""||addmoney=="0"){
            return ResultVOUtil.error(505,"充值金额异常!");
        }
        User oneUser = userService.findOneUser(userAccount);
        if (oneUser==null){
            return ResultVOUtil.error(506,"用户数据异常!");
        }
        BigDecimal userBalance = oneUser.getUserBalance();
        BigDecimal addBalance=new BigDecimal(addmoney);
        //总金额=用户余额+充值余额
        BigDecimal sumBalance=userBalance.add(addBalance);
        oneUser.setUserBalance(sumBalance);
        //更新用户余额
        userService.updateBalance(sumBalance,userAccount);
        return ResultVOUtil.success(oneUser);
    }


    //支付宝支付demo
    //https://blog.csdn.net/qq_37345604/article/details/93855402?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160428281819724835843463%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=160428281819724835843463&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v28-3-93855402.pc_search_result_cache&utm_term=%E6%94%AF%E4%BB%98%E5%AE%9Dapp%E6%94%AF%E4%BB%98&spm=1018.2118.3001.4449
    /**
     * 功能描述: 支付宝APP支付
     * @Return:
     * @Author: jinLong
     * @Date: 2020/11/2 14:03
     */
    @RequestMapping("/memberPay")
    public ResultVO pay(@RequestBody WebDTO webDTO){
        return ResultVOUtil.success(payService.AliPay(webDTO));
    }

    /**
     * 功能描述: 支付宝回调
     * @Return: com.chuangan.releasetask.VO.ResultVO
     * @Author: jinLong
     * @Date: 2020/11/2 15:10
     */
    @ResponseBody
    @RequestMapping("/Alinotify")
    public ResultVO Alinotify(HttpServletRequest request, HttpServletResponse response) {
        return ResultVOUtil.success(payService.Alinotify(request, response));
    }


    /**
     * 功能描述:进行签名
     * @Author: jinLong
     * @Date: 2020/11/9 16:09
     */
    public static Map<String, String> weixinPrePay() throws Exception {
//     ManagementAssertion.Setting setting = SettingUtils.get();
        SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
        parameterMap.put("appid", PayCommonUtil.APPID);
        parameterMap.put("mch_id", PayCommonUtil.MCH_ID);
        parameterMap.put("nonce_str", PayCommonUtil.getRandomString(32));
//        parameterMap.put("body",
//                StringUtils.abbreviate(description.replaceAll(
//                        "[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 600));
        parameterMap.put("body","微信支付-开通会员");
        parameterMap.put("out_trade_no", PayCommonUtil.getUUID32());
        parameterMap.put("fee_type", "CNY");
//        BigDecimal total = totalAmount.multiply(new BigDecimal(100));
        java.text.DecimalFormat df=new java.text.DecimalFormat("0");
//        parameterMap.put("total_fee", df.format(total));
        parameterMap.put("total_fee", 1);
        parameterMap.put("spbill_create_ip", "121.37.218.71");
        parameterMap.put("notify_url", "http://www.xyzhuanqian.com:8081/releasetask/pay/wxNotify");
        parameterMap.put("trade_type", "APP");
        String sign = PayCommonUtil.createSign("UTF-8",parameterMap);
        parameterMap.put("sign", sign);
        String requestXML = PayCommonUtil.getRequestXml(parameterMap);
        System.out.println(requestXML);
        String result = PayCommonUtil.httpsRequest(
                "https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
                requestXML);
        Map<String, String> map = null;
        try {
            map = PayCommonUtil.doXMLParse(result);

        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }
    /**
     *
     * 功能描述: 微信APP支付
     * @Return: java.lang.String
     * @Author: jinLong
     * @Date: 2020/11/16 15:36
     */
    @RequestMapping("/WechatPay")
    public static String createSignAgain(HttpServletRequest request,String sn, BigDecimal totalAmount,
                                         String description)throws Exception{
    Map<String, String> map = weixinPrePay();
    JSONObject jsonObject = new JSONObject();
    SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
        String prepay_id = map.get("prepay_id");
        parameterMap.put("appid", PayCommonUtil.APPID);
		parameterMap.put("partnerid", PayCommonUtil.MCH_ID);
		parameterMap.put("prepayid",prepay_id );
		parameterMap.put("package", "Sign=WXPay");
		parameterMap.put("noncestr", PayCommonUtil.getRandomString(32));
		parameterMap.put("timestamp", System.currentTimeMillis());
		String stringA="appid="+PayCommonUtil.APPID+"&partnerid="+PayCommonUtil.MCH_ID+"&noncestr="+ PayCommonUtil.getRandomString(32)
                +"&prepayid="+prepay_id+"&timestamp="+System.currentTimeMillis()+"&key="+PayCommonUtil.MCH_KEY;
        String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
		parameterMap.put("sign", sign);
		jsonObject.put("parameterMap",parameterMap);
		return jsonObject.toString();
}


    /**
     *
     * 功能描述: 微信回调
     * @Return: java.lang.String
     * @Author: jinLong
     * @Date: 2020/11/9 16:29
     */
    @RequestMapping("/wxNotify")
    public String wxNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            return payService.callBack(request, response);
        } catch (Exception e) {
            response.setHeader("Content-type", "application/xml");
            return "<xml>\n" +
                    "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                    "  <return_msg><![CDATA[]]></return_msg>\n" +
                    "</xml>";
        }
    }



















}
